/* $RCSFile: DesktopNavigation.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/WebControls/DesktopNavigation.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:30  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Globalization;

using AddonNice.Helpers;
using AddonNice.Core;
using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Security;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;

using Trace2    =   System.Diagnostics.Trace;
using Cache2    =   AddonNice.Settings.Cache.CurrentCache;

namespace AddonNice.UI.WebControls
{
	/// <summary>
	/// Represents a flat navigation bar. One dimension. 
	/// Can render horizontally or vertically.
	/// </summary>
	public class DesktopNavigation : DataList, INavigation, IPortalMenu
	{
        PortalSettings _portalSettings; 
        protected PortalSettings portalSettings 
        {
            get 
            {
                if ( _portalSettings == null )
                    _portalSettings = (PortalSettings)HttpContext.Current.Items[StStr.strPortalSettings];
                return _portalSettings;
            }
        }

        #region INavigation implementation

		private bool _useTabNameInUrl = false;

		/// <summary> 
		/// Indicates if control show the tabname in the url 
		/// </summary> 
		[ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] 
		public bool UseTabNameInUrl 
		{ 
			get{return _useTabNameInUrl;} 
			set{_useTabNameInUrl = value;} 
		} 
		
		private BindOption _bind = BindOption.BindOptionTop;
		private bool _autoBind = false;
		private int _definedParentTab = -1;
		/// <summary>
		/// Indicates if control should bind when loads
		/// </summary>
		[
		Category("Data"),
		PersistenceMode(PersistenceMode.Attribute)
		]
		public bool AutoBind
		{
			get{return _autoBind;}
			set{_autoBind = value;}
		}

		/// <summary>
		/// Describes how this control should bind to db data
		/// </summary>
		[
		Category("Data"),
		PersistenceMode(PersistenceMode.Attribute)
		]
		public BindOption Bind
		{ 
			get {return _bind;}
			set
			{
				if(_bind != value)
				{
					_bind = value;
				}
			}
		}

		/// <summary>
		/// defines the parentTabID when using BindOptionDefinedParent
		/// </summary>
		[
		Category("Data"),
		PersistenceMode(PersistenceMode.Attribute)
		]
		public int ParentPageID
		{ 
			get {return _definedParentTab;}
			set
			{
				if(_definedParentTab != value)
				{
					_definedParentTab = value;
				}
			}
		}

		#endregion
        
        bool _HideUnderCrm = true;
		/// <summary> 
		/// Should control be hidden when under Crm 
        /// default: true
		/// </summary> 
		[ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] 
		public bool HideUnderCrm
		{ 
			get{return _HideUnderCrm;} 
			set{_HideUnderCrm = value;} 
		} 

        bool _IsPortalMenus = false;
		/// <summary> 
		/// Should control act as a portal menu
        /// default: false
		/// </summary> 
		[ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] 
		public bool IsPortalMenus 
		{ 
			get{return _IsPortalMenus;} 
			set{_IsPortalMenus = value;} 
		} 
        
        
        #region IPortalMenu implementation
        
        public void ResetCache()
        {
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DesktopNavigation ResetCache BEG Items.Count: {0}.", Items.Count),NavTraceSwitch.Sw.Info);
            Cache2.RemoveGlobalPagesCacheKey();
        }

        public void Rebind()
        {
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DesktopNavigation Rebind BEG Items.Count: {0}.", Items.Count),NavTraceSwitch.Sw.Info);
            innerDataSource =   null;
            DataBind();
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DesktopNavigation Rebind END IsPostBack: {0}.", Items.Count),NavTraceSwitch.Sw.Info);
        }
       
        public bool SelectMenuItem(int wPageId)
        {
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DesktopNavigation SelectMenuItem BEG PageId: {0}.", wPageId),NavTraceSwitch.Sw.Info);
            // Not implemented
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]DesktopNavigation SelectMenuItem not Implemented END.",NavTraceSwitch.Sw.Info);
            return false;
        }

        public Control AjaxControl
        {
            get
            {
                return this;
            }
        }

        public bool ShouldRegisterInAjaxManager
        {
            get
            {
                return true;
            }
        }

        #endregion IPortalMenu

		private System.Web.UI.WebControls.RepeatDirection rd = System.Web.UI.WebControls.RepeatDirection.Horizontal;
		[DefaultValue(System.Web.UI.WebControls.RepeatDirection.Horizontal)]
		public override System.Web.UI.WebControls.RepeatDirection RepeatDirection
		{
			get{return rd;}
			set{rd = value;}
		}
		
        private AuthorizedPageStripDetail innerDataSource = null;

        /// <summary>
		/// DataSource
		/// </summary>
		public override object DataSource
		{
			get
			{
				if (innerDataSource == null)
				{
                    int CurrentParentPageID =   -1;
					innerDataSource         =   new AuthorizedPageStripDetail(Bind,ParentPageID,CurrentParentPageID);
                    ParentPageID            =   innerDataSource.ParentPageID;
				}
				return innerDataSource;
			}
			set
			{
				innerDataSource = value as AuthorizedPageStripDetail ;                
			}
		}

        protected override void OnInit(EventArgs e)
        {
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DesktopNavigation OnInit BEG IsPostBack: {0}, AutoBind: {1}.", Page.IsPostBack,AutoBind),NavTraceSwitch.Sw.Info);
            // Registers in portal
            if ( IsPortalMenus )
                portalSettings.AddPortalMenu(this);
            base.OnInit(e);
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DesktopNavigation OnInit END count: {0}.", Items.Count),NavTraceSwitch.Sw.Info);
        }

        /// <summary>
		/// Default constructor
		/// </summary>
		public DesktopNavigation()
		{
			EnableViewState     =   false;
			Load                +=  new System.EventHandler(LoadControl);
		}

		private void LoadControl(object sender, System.EventArgs e)
		{
            if (HideUnderCrm && PortalSettings.IsUnderCRM)
            {
                Visible         =   false;
                return;
            }
            if(AutoBind)
				DataBind();
		}


		private int GetSelectedTab(int parentPageID, int activePageID , PageStripDetailsList allTabs)
		{
            bool isForm                 =   (Config.AuthenticationMode == System.Web.Configuration.AuthenticationMode.Forms );
            IAddonNiceUser    curUser   =   PortalSettings.CurrentUser;
            bool isAuthenticated        =   ( curUser != null ) ? !curUser.IsAnonymous : false;
			for( int i = 0 ; i < allTabs.Count; i++)
			{
                PageStripDetails tmpTab = allTabs[i];
				if (tmpTab.OkForMenus && 
                    ( isForm || ( !isForm && !tmpTab.FormsOnly ) ) && 
                    ( isAuthenticated || ( !isAuthenticated && !tmpTab.AuthenticatedOnly ) ) && 
                    (tmpTab.PageID == activePageID) )
				{
                    int selectedPageID  =   activePageID;
                    if (tmpTab.ParentPageID != parentPageID) 
					{
                        selectedPageID  =   GetSelectedTab(parentPageID, tmpTab.ParentPageID, allTabs);
                        return selectedPageID;
					}	
                    return selectedPageID;
				}
			}
			return StStr.PageIDNotAssigned;
		}					   																				   

	}
}

